package database

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"goTool/common"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlserver"
	gorm2 "gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

/*
   ### gORM连接实例 ###
*/
func OrmConn(cfg DbConfig) *gorm.DB {
	ConnStr := ""

	switch cfg.Dialect {
	case "mysql":
		ConnStr = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.UserName, cfg.Password, cfg.Host, cfg.Port, cfg.DbName)
	case "postgres":
		ConnStr = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai", cfg.Host, cfg.Port, cfg.UserName, cfg.Password, cfg.DbName)
	case "mssql":
		ConnStr = fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s", cfg.UserName, cfg.Password, cfg.Host, cfg.Port, cfg.DbName)
	}

	conn, err := gorm.Open(cfg.Dialect, ConnStr)
	common.IsError(err)

	// 配置数偏少于数据库配置的最大连接数(mysql查询:show variables like '%max_connections%')
	conn.DB().SetMaxIdleConns(9)
	conn.DB().SetMaxOpenConns(9)
	conn.DB().SetConnMaxLifetime(9 * time.Second)

	conn.LogMode(cfg.Debug)

	return conn
}

/*
   ###gORM2连接实例 ###(go version >=1.14)
   文档:https://www.kancloud.cn/sliver_horn/gorm/1861155
*/
func OrmConnV2(cfg DbConfig) *gorm2.DB {
	var dialectStr gorm2.Dialector
	level := logger.Error
	if cfg.Debug {
		level = logger.Info
	}

	switch cfg.Dialect {
	case "mysql":
		ConnStr := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.UserName, cfg.Password, cfg.Host, cfg.Port, cfg.DbName)
		dialectStr = mysql.Open(ConnStr)
	case "postgres":
		ConnStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai", cfg.Host, cfg.Port, cfg.UserName, cfg.Password, cfg.DbName)
		dialectStr = postgres.Open(ConnStr)
	case "mssql":
		ConnStr := fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s", cfg.UserName, cfg.Password, cfg.Host, cfg.Port, cfg.DbName)
		dialectStr = sqlserver.Open(ConnStr)
	}

	conn, err := gorm2.Open(dialectStr, &gorm2.Config{Logger: logger.Default.LogMode(level)})
	common.IsError(err)

	sqlDB, err := conn.DB()
	common.IsError(err)

	// 配置数偏少于数据库配置的最大连接数(mysql查询:show variables like '%max_connections%')
	sqlDB.SetMaxIdleConns(9)
	sqlDB.SetMaxOpenConns(9)
	sqlDB.SetConnMaxLifetime(9 * time.Second)

	return conn
}
